<template>
  <view class="dynamic-form__attachment-downlaod">
    <view
      class="dynamic-form__attachment-item"
      v-for="attachment in attachmentList"
      :key="attachment.name"
      @click="handleDownloadAttachment(attachment)"
    >
      <image :src="isImage(attachment.extname) ? attachment.url : filePreview(attachment.extname)" />
      <!-- <view>{{ attachment.name }}</view> -->
    </view>
  </view>
</template>

<script>
export default {
  props: {
    attachmentList: {
      type: Array,
      default: [],
    },
  },
  components: {},
  data() {
    return {}
  },
  computed: {},
  created() {},
  mounted() {},
  watch: {},
  methods: {
    isImage(extname) {
      return ['jpg', 'jpeg', 'png', 'JPEG'].includes(extname)
    },
    async handleDownloadAttachment(attachment) {
      console.log(attachment)
      if (this.isImage(attachment.extname)) {
        //图片预览
        uni.previewImage({
          current: attachment.url,
          urls: this.attachmentList.filter((attachment) => this.isImage(attachment.extname)).map((item) => item.url),
        })
      } else {
        //附件下载
        const [err, { tempFilePath }] = await uni.downloadFile({
          url: attachment.url,
          timeout: 2000,
        })
        console.log(tempFilePath)
        if (tempFilePath) {
          await uni.openDocument({
            filePath: tempFilePath,
            fileType: attachment.extname,
          })
        }
      }
    },
    filePreview(extname) {
      console.log(extname)
      if (['doc', 'docx'].includes(extname)) {
        return '/static/img/icons/word.png'
      } else if (['xls', 'xlsx'].includes(extname)) {
        return '/static/img/icons/excel.png'
      } else if (['ppt', 'pptx'].includes(extname)) {
        return '/static/img/icons/ppt.png'
      } else if (extname === 'pdf') {
        return '/static/img/icons/pdf.png'
      }
    },
  },
}
</script>

<style lang="scss">
.dynamic-form__attachment-downlaod {
  overflow: hidden;
  display: flex;
  flex-wrap: wrap;
}
.dynamic-form__attachment-item {
  border: 1px solid #eeeeee;
  border-radius: 5px;
  padding: 8px 10px;
  display: flex;
  margin: 10rpx;
  & image {
    width: 120rpx;
    height: 120rpx;
  }
  // & > view:first-child {
  //   flex: 1;
  //   color: #666;
  //   word-break: break-all;
  //   word-wrap: break-word;
  // }
}
</style>
